package com.example.shunt;

import com.example.model.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * Created with IntelliJ IDEA.
 * ClassName: ProcessStream
 * Package: com.example.shunt
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-07-22
 * Time: 21:05
 */

//分流算子
public class ProcessStream {

    public static void main(String[] args) throws Exception {
        //转换算子 filter 过滤算子也可以分流 但是同样的数据执行两边效率低

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        final SingleOutputStreamOperator<WaterSensor> map = env.socketTextStream("hadoop102", 7777)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] s = value.split(" ");

                        return new WaterSensor(s[0], Long.valueOf(s[1]), Integer.valueOf(s[2]));
                    }
                });

        //内部ID别搞错了
        OutputTag<WaterSensor> tag1 = new OutputTag<>("s1",Types.POJO(WaterSensor.class));
        OutputTag<WaterSensor> tag2 = new OutputTag<>("s2",Types.POJO(WaterSensor.class));

        /**
         * 侧输出流使用process算子  处理函数
         * 使用上下文获取到侧输出流方式 output()方法
         * 参数是 OutputTag 创建全局变量 从主流中获取侧输出标签
         * 而且OutputTag的类型是 TypeInformation
         */


        //测输出流 Process 过程
        SingleOutputStreamOperator<WaterSensor> process = map.process(new ProcessFunction<WaterSensor, WaterSensor>() {
            /**
             * 测输出流 使用要的是process 处理函数
             * @param value 输入的值
             * @param ctx 利用上下文输出的值 output() 方法可以输入任意以的值
             * @param out Collector 像主流发送数据
             * @throws Exception
             */
            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<WaterSensor> out) throws Exception {
                //编写测输出流逻辑
                if ("s1".equals(value.getId())) {
                    //output()方法的参数是 OutPutTag 输出标签 指定测流的名字,第二个参数是测流的值
                    ctx.output(tag1,value);
                } else if ("s2".equals(value.getId())) {
                    ctx.output(tag2, value);
                } else {
                    //剩余元素 就从主流流出
                    out.collect(value);
                }
            }
        });

        process.print();

        //测输出流的内容要从主流当中获取 参数是 OutputTag标签 所以上面不能创建匿名内部类
        process.getSideOutput(tag1).print("s1-");
        process.getSideOutput(tag2).print("s2-");

        env.execute();

    }
}
